import uvicorn
from fastapi import FastAPI
from package.fastapi.extend import mount_local_static
from package.task import task
from setting import setting


def create_app():
    """创建fastapi对象"""
    kwargs = {}
    if getattr(setting, 'prod', True) is True:  # 正式环境关闭swagger文档
        kwargs = dict(title='Myli', contact={'user': 'miaoyun@miaoyun.io'},
                      swagger_ui_parameters={"defaultModelsExpandDepth": 1}, docs_url=None, redoc_url=None)
    fast_app = FastAPI(**kwargs)
    return fast_app


def register_router(fast_app):
    prefix = '/api/v1'
    from router import devops, source
    fast_app.include_router(devops.router_devops, prefix=prefix)
    fast_app.include_router(source.router_source, prefix=prefix)
    fast_app.include_router(devops.router_external, prefix=prefix)


def register_permission(fast_app):
    """权限注册"""
    from fastapi.security import OAuth2PasswordBearer
    from package.fastapi.security import security_hash, security_jwt, security_rsa, permission
    permission.init(enabled=False, oauth2_scheme=OAuth2PasswordBearer(tokenUrl='/api/v1/auth/token', auto_error=False))


def register_middle():
    """中间件注册"""
    from package.connector.sql_db import db
    from package.connector.redis_db import rdb
    from package.connector.elastic_db import es_db
    db.init(url=setting.pg_uri, pool_pre_ping=True)
    rdb.init(host=setting.redis_host, password=setting.redis_password)
    es_db.init(hosts=f'http://{setting.elasticsearch_host}:{setting.elasticsearch_port}')
    task.init_config(store_configure=dict(host=setting.redis_host, password=setting.redis_password,
                                          jobs_key='collector2:apscheduler',
                                          run_times_key='collector2:apscheduler.runtime'),
                     default_configure={'coalesce': True, 'max_instances': 3})
    task.scheduler.state = 2  # 停止状态 http请求服务与 task定时任务分开


def register_middleware(fast_app):
    pass


app = create_app()
mount_local_static(app)
register_permission(app)

register_middle()
register_middleware(app)
register_router(app)


if __name__ == '__main__':
    uvicorn.run('main:app', host='0.0.0.0', port=8003, reload=True)
